﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

public partial class hibernateConfig : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/plain";
    }

    public string TableName
    {
        get
        {
            return Request["TableName"];
        }
    }

    public string ClassName
    {
        get
        {
            return StringTools.GetName(TableName);
        }
    }

    public List<Code.DAL.Table> CurrentDables
    {
        get
        {
            return (List<Code.DAL.Table>)Session["Tables"];
        }
    }

    public Code.DAL.Table CurrentTable
    {
        get
        {
            return CurrentDables.Find(x => x.Name == TableName);
        }
    }

    public string IdStr
    {
        get
        {
            StringBuilder sb = new StringBuilder();
            if (CurrentTable.Columns.Where(x => x.IsKey).Count() > 1)
            {
                var ids=CurrentTable.Columns.Where(x => x.IsKey).ToList();
                sb.AppendLine("      <composite-id>");
                foreach(var c in ids)
                {
                    sb.AppendLine("           <key-property name=\"" + StringTools.GetName(c.Name) + "\" column=\"[" + c.Name + "]\" " + StringTools.GetTypeName(c.Type) + "  />");
                }
                sb.AppendLine("      </composite-id>");
            }
            else
            {
                var cols = CurrentTable.Columns.Where(x => x.IsKey).ToList();
                foreach (var c in cols)
                {
                    sb.AppendLine("      <id name=\"" + StringTools.GetName(c.Name) + "\" column=\"[" + c.Name + "]\" " + StringTools.GetTypeName(c.Type) + " >");
                    if(c.IsIdentity)
                    {
                        sb.AppendLine("           <generator class=\"native\"></generator>");
                    }
                    sb.AppendLine("      </id>");
                }
            }
            return sb.ToString() ;
        }
    }

    public string Cols
    {
        get
        {
            var cols = CurrentTable.Columns.Where(x => x.IsKey==false).ToList();
            StringBuilder sb=new StringBuilder();
            foreach (var c in cols)
            {
                sb.AppendLine("      <property name=\"" + StringTools.GetName(c.Name) + "\" column=\"[" + c.Name + "]\" " + StringTools.GetTypeName(c.Type) + " />");
            }
            return sb.ToString();
        }
    }
}